<template>
  <div>
    <div id="myCover" :class="isFullActive ? '' : 'setZindex'">
      <div class="gantt__header">
        <!-- <p>test:{{ isFullActive }}</p> -->
        <div class="gantt__header--left">
          <GanttUse
            v-if="projectLeader"
            @emitImportGantt="handleFileChange"
            @emitExportGantt="exportGanttData"
            :isDataLength="isDataLength"
          />
        </div>

        <div>
          <el-button-group>
            <el-button type="primary" @click="handleFull">
              <span v-show="isFullActive"
                ><i class="el-icon-full-screen"></i> 全屏</span
              >
              <span v-show="!isFullActive"
                ><i class="el-icon-crop"></i> 还原</span
              >
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-d-arrow-left"
              @click="handleExpend"
              >{{ isGridView ? "拉伸" : "还原" }}</el-button
            >
            <el-button type="primary" icon="el-icon-date" @click="handleYear"
              >年</el-button
            >
            <el-button type="primary" icon="el-icon-date" @click="handleMonth"
              >月</el-button
            >
            <el-button type="primary" icon="el-icon-date" @click="handleWeek"
              >周</el-button
            >
            <el-button type="primary" icon="el-icon-date" @click="handleDay"
              >日</el-button
            >
          </el-button-group>
        </div>
      </div>
      <div ref="ganttRef" class="gantt__wrap"></div>
    </div>
    <el-dialog
      :title="dbClickFlag ? '编辑' : '创建'"
      v-model="dialogVisible"
      destroy-on-close
      @closed="handleClose"
      width="600px"
    >
      <div class="dialog-wrap">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rulesRules"
          label-width="100px"
        >
          <el-form-item label="类型" prop="type">
            <el-row>
              <el-select
                v-model="ruleForm.type"
                placeholder="请选择类型"
                @change="handleChangeType"
              >
                <el-option label="任务" value="task"></el-option>
                <el-option label="项目" value="project"></el-option>
                <el-option label="里程碑" value="milestone"></el-option>
              </el-select>
            </el-row>
          </el-form-item>
          <el-form-item label="名称" prop="text" placeholder="请填写名称">
            <el-input v-model="ruleForm.text"></el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type !== 'milestone'"
            label="进度"
            prop="progress"
          >
            <el-slider
              style="width: 100%"
              v-model="ruleForm.progress"
              :max="100"
              :min="0"
              show-input
              @change="onParseint"
            ></el-slider>
          </el-form-item>
          <el-form-item
            v-if="['task', 'milestone'].includes(ruleForm.type)"
            label="开始时间"
            prop="start_date"
          >
            <el-date-picker
              v-model="ruleForm['start_date']"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type === 'task'"
            label="工期"
            prop="duration"
          >
            <el-input-number :min="1" v-model="ruleForm.duration" />
            <span>&emsp;<i class="el-icon-info"></i>工期为工作日时间</span>
          </el-form-item>
          <el-form-item
            label="子计划负责人"
            v-if="isCanEmpower || isRootNode"
            prop="privilegeUserId"
          >
            <el-select
              v-model="ruleForm.privilegeUserId"
              filterable
              remote
              clearable
              placeholder="请输入姓名"
              :remote-method="getTableData"
            >
              <!-- reserve-keyword -->
              <!-- :loading="loading" -->
              <el-option
                v-for="item in userList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <template v-if="false">
            <div style="padding: 15px">关联流程</div>
            <el-form-item label="验收类型">
              <el-select placeholder="请选择类型" v-model="formSearch.billType">
                <el-option
                  v-for="item in typeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联流程">
              <el-select
                v-model="ruleForm.billName"
                clearable
                filterable
                remote
                placeholder="请输入单据名称"
                :remote-method="handleSearch"
                value-key="value"
              >
                <!-- reserve-keyword -->
                <el-option
                  v-for="item in tableData"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
// import "dhtmlx-gantt/codebase/skins/dhtmlxgantt_material.css";
import { gantt } from "dhtmlx-gantt";
import { getUserList, postUserInfo } from "/@/api/user";

import {
  defineComponent,
  ref,
  onMounted,
  nextTick,
  reactive,
  onBeforeMount,
  onUnmounted,
  unref
} from "vue";
import { useEventListener } from "@vueuse/core";
import { useSettingStoreHook } from "/@/store/modules/settings";
import { postBills } from "/@/api/work";
import dayjs from "dayjs";
import { downloadXml } from "/@/utils/download";
import GanttUse from "./GanttUse.vue";
import { ElMessageBox } from "element-plus";
import NotifMessage from "/@/utils/message/notification";
import { useRoute } from "vue-router";
import {
  postSaveAddlink,
  postSaveDeletelink,
  postSaveAddtask,
  postSaveDeletetask,
  postSaveUpdatetask,
  // postGetGanttCurrentInfo,
  postProgressInfo
} from "/@/api/flowProgress";

// import { getWeekday } from "/@/utils/compareDate";

// import test from "./test.json";

export default defineComponent({
  components: {
    GanttUse
  },
  props: {
    tasks: {
      default: () => {
        return {
          data: [],
          links: []
        };
      }
    },
    projectLeader: {
      type: Boolean,
      default: true
    },
    isDataLength: {
      type: Boolean,
      default: false
    }
  },
  emits: ["getGanttData", "emitSaveToGo"],
  setup(props, { emit }) {
    // const router = useRouter();
    const route = useRoute();
    // 控制全屏时使用
    const pureSetting = useSettingStoreHook();
    let isGridView = ref<boolean>(true);
    let isFullActive = ref<boolean>(true);
    const ganttRef = ref<HTMLElement | null>(null) as any;
    const ruleFormRef = ref<HTMLFormElement | null>(null) as any;
    let dialogVisible = ref(false);
    let currentGanttId = ref<any>(null);
    let dbClickFlag = ref(false); // 双击标识
    let headerTitle = ref("add");
    let ruleForm = reactive({
      type: "",
      text: "",
      progress: 0,
      start_date: "",
      duration: 1,
      parent: 0,
      billName: null,
      billId: null,
      privilegeUserId: ""
    });

    // 是否可以设置子计划负责人
    let isCanEmpower = ref<boolean>(false);
    let isRootNode = ref<boolean>(false);
    let userList = ref([]);

    let isEditStatus = ref(props.projectLeader);

    const typeList = [
      { value: "1", label: "到货验收" },
      { value: "5", label: "有监理隐蔽验收" },
      { value: "6", label: "无监理隐蔽验收" },
      { value: "7", label: "有监理土建竣工验收" },
      { value: "8", label: "无监理土建竣工验收" },
      { value: "9", label: "开工审批" },
      { value: "10", label: "材料审批" },
      { value: "11", label: "质量管理施工类" },
      { value: "15", label: "质量管理设备类" }
    ];

    let formSearch = reactive({
      billType: "",
      pageNum: 1,
      pageSize: 100
    });

    let tableData = ref([]);

    let rulesRules = reactive({
      type: [
        {
          required: true,
          message: "请选择类型",
          trigger: "change"
        }
      ],
      text: [
        {
          required: true,
          message: "请填写名称",
          trigger: "change"
        }
      ],
      progress: [
        {
          required: true,
          message: "请填写进度",
          trigger: "change"
        }
      ],
      duration: [
        {
          required: true,
          message: "请输入工期",
          trigger: "change"
        }
      ],
      start_date: [
        {
          required: true,
          message: "请选择开始时间",
          trigger: "change"
        }
      ]
    });

    function setting() {
      gantt.plugins({
        marker: true,
        fullscreen: true,
        critical_path: true,
        auto_scheduling: true,
        tooltip: true
        // undo: true
        // lightbox: false
      });

      function getWeekOfMonthNumber(date) {
        let adjustedDate = date.getDate() + date.getDay();
        let prefixes = ["0", "1", "2", "3", "4", "5"];
        return parseInt(prefixes[0 | (adjustedDate / 7)]) + 1;
      }

      var zoomConfig = {
        levels: [
          {
            name: "day",
            scale_height: 50,
            min_column_width: 80,
            scales: [
              { unit: "year", format: "%Y" },
              { unit: "month", format: "%Y, %F" },
              {
                unit: "day",
                step: 1,
                format: "%M %d",
                css: function (date) {
                  if (!gantt.isWorkTime(date)) {
                    return "weekend";
                  }
                }
              }
            ]
          },
          {
            name: "week",
            scale_height: 50,
            min_column_width: 50,
            scales: [
              {
                unit: "week",
                step: 1,
                format: function (date) {
                  return "Week #" + getWeekOfMonthNumber(date);
                }
              },
              {
                unit: "day",
                step: 1,
                format: "%j %D",
                css: function (date) {
                  if (!gantt.isWorkTime(date)) {
                    return "weekend";
                  }
                }
              }
            ]
          },
          {
            name: "month",
            scale_height: 50,
            min_column_width: 120,
            scales: [
              { unit: "month", format: "%Y, %F" },
              {
                unit: "week",
                format: function (date) {
                  return "Week #" + getWeekOfMonthNumber(date);
                }
              }
            ]
          },
          {
            name: "year",
            scale_height: 50,
            min_column_width: 30,
            scales: [{ unit: "year", step: 1, format: "%Y" }]
          }
        ]
      };

      // 设置年月日的缩放
      gantt.ext.zoom.init(zoomConfig);
      gantt.ext.zoom.setLevel("day");

      // gantt.config.scale_height = 50;
      // 自动滚动
      gantt.config.autoscroll = true;
      gantt.config.autoscroll_speed = 40;
      // gantt.config.subscales = [
      //   {
      //     unit: "year",
      //     step: 1,
      //     date: "%Y"
      //   }
      // ];
      // gantt.config.date_scale = "%M %d日";
      // gantt.config.grid_width = 380;

      gantt.locale.labels.deadline_enable_button = "Set";
      gantt.locale.labels.deadline_disable_button = "Remove";

      // 配置工作日，一周5天
      gantt.config.work_time = true;
      // 拖拽task的时候，自动将起始时间和结束时间矫正为工作日
      gantt.config.correct_work_time = true;
      gantt.config.skip_off_time = true;

      // 配置结束时间  https://docs.dhtmlx.com/gantt/desktop__loading.html#taskenddatedisplayampinclusiveenddates
      // gantt.templates.task_end_date = function (date) {
      //   return gantt.templates.task_date(new Date(date.valueOf() - 1));
      // };

      // var gridDateToStr = gantt.date.date_to_str("%Y-%m-%d");
      // gantt.templates.grid_date_format = function (date, column) {
      //   if (column === "end_date") {
      //     return gridDateToStr(new Date(date.valueOf() - 1));
      //   } else {
      //     return gridDateToStr(date);
      //   }
      // };

      // 标题配置
      gantt.templates.grid_header_class = function (columnName) {
        if (columnName == "buttons" && !props.projectLeader) {
          return "hideElement";
        }
      };

      //列配置

      var colHeader =
        '<div class="gantt_grid_head_cell gantt_grid_head_add" onclick="gantt.createTask()"></div>';
      var colContent = function (task) {
        // console.log(task, "test-task");
        // TODO 还需要进行全局前置判断
        if (props.projectLeader) {
          return `<i class="fa gantt_button_grid gantt_grid_edit fa-pencil" id="gantt_edit"></i>
          <i class="fa gantt_button_grid gantt_grid_add fa-plus" id="gantt_add"></i>
          <i class="fa gantt_button_grid gantt_grid_delete fa-times" id="gantt_delete"></i>`;
        } else {
          if (task.canEdit && !props.projectLeader) {
            // return `<i class="fa gantt_button_grid gantt_grid_edit fa-pencil" id="gantt_auth_edit"></i>`;
            return `<i class="fa gantt_button_grid gantt_grid_edit fa-pencil" id="gantt_edit"></i>
          <i class="fa gantt_button_grid gantt_grid_add fa-plus" id="gantt_add"></i>
          <i class="fa gantt_button_grid gantt_grid_delete fa-times" id="gantt_delete"></i>`;
          } else {
            return ``;
          }
        }
      };

      // var durationEditor = {
      //   type: "number",
      //   map_to: "duration",
      //   min: 0,
      //   max: 100
      // };

      gantt.config.columns = [
        {
          name: "overdue",
          label: "",
          width: 26,
          min_width: 26,
          template: function (obj) {
            if (obj.end_date) {
              var deadline = gantt.date.parseDate(obj.end_date, "xml_date");
              if (deadline <= new Date() && obj.progress !== 1) {
                return '<div class="overdue-indicator">!</div>';
              }
            }
            return "<div></div>";
          }
        },
        {
          name: "text",
          label: "名称",
          align: "left",
          tree: true,
          min_width: 200,
          width: "*",
          resize: true
        },
        {
          name: "start_date",
          label: "时间",
          align: "center",
          resize: true,
          min_width: 160,
          width: 160,
          template: function (obj) {
            const startTime = obj.start_date ? obj.start_date : "";
            const newDate = JSON.parse(JSON.stringify(obj.end_date));
            let x: number = +dayjs(newDate).format("x");
            if (obj.duration) {
              x = +dayjs(newDate).format("x") - 16 * 60 * 60 * 1000;
            }

            const endTime = dayjs(x).format("YYYY-MM-DD");
            return `<div>${dayjs(startTime).format(
              "YYYY-MM-DD"
            )}~${endTime}</div>`;
          }
        },
        // {
        //   name: "end_date",
        //   label: "结束时间",
        //   align: "center",
        //   min_width: 80,
        //   width: 80
        // },
        {
          name: "duration",
          label: "工期",
          align: "center",
          resize: true,
          min_width: 50,
          width: 50
          // editor: durationEditor
        },
        {
          name: "progress",
          label: "进度",
          align: "center",
          resize: true,
          min_width: 60,
          width: 60,
          template: function (obj) {
            if (obj.progress <= 1) {
              return obj.progress
                ? parseInt(Math.round(obj.progress * 10000) / 100) + "%"
                : "0%";
            } else {
              return parseInt(obj.progress) + "%";
            }
          }
        },
        // { name: "add", label: "", width: 44, resize: true, hide: false }
        {
          name: "buttons",
          label: colHeader,
          width: 85,
          min_width: 85,
          template: colContent
        }
      ];

      // gantt.config.columns = [
      //   { name: "text", label: "Task name", tree: true, width: "*" },
      //   {
      //     name: "progress",
      //     label: "Progress",
      //     width: 80,
      //     align: "center",
      //     template: function (item) {
      //       if (item.progress >= 1) return "Complete";
      //       if (item.progress == 0) return "Not started";
      //       return Math.round(item.progress * 100) + "%";
      //     }
      //   }
      // ];
      // gantt.locale.labels["section_progress"] = "Progress";
      gantt.config.layout = {
        css: "gantt_container",
        cols: [
          {
            width: 580,
            min_width: 580,
            hide_empty: true,
            rows: [
              {
                view: "grid",
                scrollX: "gridScroll",
                scrollable: true,
                scrollY: "scrollVer"
              }
              // { view: "scrollbar", id: "gridScroll", group: "horizontal" }
            ]
          },
          { resizer: true, width: 1 },
          {
            rows: [
              { view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer" },
              { view: "scrollbar", id: "scrollHor", group: "horizontal" }
            ]
          },
          { view: "scrollbar", id: "scrollVer" }
        ]
      };

      // 任务创建事件
      gantt.attachEvent(
        "onTaskCreated",
        function () {
          // if (item.duration == 1) {
          //   item.duration = 24;
          // }
          if (props.projectLeader) {
            dialogVisible.value = true;
          }

          // const res = {
          //   duration: 10,
          //   end_date: "2021-12-12 00:00:00",
          //   id: new Date(),
          //   parent: 0,
          //   progress: 0,
          //   start_date: "2021-12-03 00:00:00",
          //   text: "新项目test",
          //   type: "task"

          //   //  duration: 1,
          //   //   end_date: `Fri Dec 03 2021 00:00:00 GMT+0800 (中国标准时间) {}`,
          //   //   id: 1638507626827,
          //   //   parent: 0,
          //   //   progress: "0.3",
          //   //   start_date: `Thu Dec 02 2021 00:00:00 GMT+0800 (中国标准时间) {}`,
          //   //   text: "新项目",
          //   //   type: "project",
          // };

          // gantt.addTask(res, 0);
          // gantt.refreshData();
          // gantt.render();

          return false;
        },
        null
      );
      // gantt.attachEvent(
      //   "onTaskLoading",
      //   function (task) {

      //     console.log( task, "task")
      //   // if (task.deadline)
      //   //   task.deadline = gantt.date.parseDate(task.deadline, "xml_date");
      //     return true;
      //   },
      // null
      // );

      gantt.attachEvent(
        "onTaskDblClick",
        function () {
          // currentGanttId.value = id;
          // dbClickFlag.value = true;
          // dialogVisible.value = true;

          // console.log(id, e);
          // const tasks = Object.values(gantt.getDatastore("task").pull);
          // const checkTask = tasks.filter(item => {
          //   // @ts-ignore
          //   return item.id == id;
          // });
          // console.log(checkTask, "task");
          // // @ts-ignore
          // // ruleForm = checkTask[0];
          // // @ts-ignore
          // ruleForm.type = checkTask[0]?.type ?? "";
          // // @ts-ignore
          // ruleForm.text = checkTask[0]?.text ?? "";
          // // @ts-ignore
          // ruleForm.progress = checkTask[0]?.progress ?? "";
          // ruleForm.progress = ruleForm.progress * 100;
          // // @ts-ignore
          // ruleForm.start_date = checkTask[0]?.start_date ?? "";

          // if (ruleForm.start_date) {
          //   const chacheDate = dayjs(ruleForm.start_date).format("YYYY-MM-DD");
          //   ruleForm.start_date = `${chacheDate} 00:00:00`;
          // }
          // // @ts-ignore
          // ruleForm.duration = checkTask[0]?.duration ?? null;

          // // @ts-ignore
          // ruleForm.parent = checkTask[0]?.parent ?? "";
          // // @ts-ignore
          // ruleForm.billName = checkTask[0]?.billName ?? "";
          // // @ts-ignore
          // ruleForm.billId = checkTask[0]?.billId ?? "";
          // // @ts-ignore
          // if (ruleForm.billName) {
          //   tableData.value = [
          //     { value: ruleForm.billId, label: ruleForm.billName }
          //   ];
          // }
          // // @ts-ignore
          // // ruleForm[`$source`] = checkTask[0][`$source`];
          // // ruleForm[`$target`] = checkTask[0][`$target`];

          // console.log(ruleForm, "ruleForm--edit");
          return false;
        },
        null
      );

      // 任务栏点击事件，获取点击的当前任务ID
      gantt.attachEvent(
        "onTaskClick",
        async function (id, e) {
          console.log(id, e.target.id, "click__item");

          if (e.target.id === "gantt_edit") {
            // gantt.showLightbox(id);
            currentGanttId.value = id;
            dbClickFlag.value = true;
            dialogVisible.value = true;

            console.log(id, e);
            const checkTask = gantt.getTask(id);

            if (checkTask?.privilegeUserId) {
              // @ts-ignore
              userList.value = await searchUserName([
                checkTask.privilegeUserId
              ]);
              // @ts-ignore
              ruleForm.privilegeUserId = checkTask?.privilegeUserId ?? "";
            }

            isCanEmpower.value = checkTask.canEmpower;
            // const tasks = Object.values(gantt.getDatastore("task").pull);
            // const checkTask = tasks.filter(item => {
            //   // @ts-ignore
            //   return item.id == id;
            // });
            console.log(checkTask, "task");
            // @ts-ignore
            // ruleForm = checkTask[0];
            // @ts-ignore
            ruleForm.type = checkTask?.type ?? "";
            // @ts-ignore
            ruleForm.text = checkTask?.text ?? "";
            // @ts-ignore
            ruleForm.progress = checkTask?.progress ?? "";
            if (ruleForm.progress < 1) {
              ruleForm.progress = parseInt(ruleForm.progress * 100);
            }
            // @ts-ignore
            ruleForm.start_date = checkTask?.start_date ?? "";

            if (ruleForm.start_date) {
              const chacheDate = dayjs(ruleForm.start_date).format(
                "YYYY-MM-DD"
              );
              ruleForm.start_date = `${chacheDate} 00:00:00`;
            }
            // @ts-ignore
            ruleForm.duration = checkTask?.duration ?? "";

            // @ts-ignore
            ruleForm.parent = checkTask?.parent ?? "";
            // @ts-ignore
            ruleForm.billName = checkTask?.billName ?? "";
            // @ts-ignore
            ruleForm.billId = checkTask?.billId ?? "";

            // @ts-ignore
            if (ruleForm.billName) {
              tableData.value = [
                { value: ruleForm.billId, label: ruleForm.billName }
              ];
            }
          } else if (e.target.id === "gantt_add") {
            // const links = Object.values(gantt.getDatastore("link").pull);
            // const tasks = Object.values(gantt.getDatastore("task").pull);
            // console.log(links, tasks);
            currentGanttId.value = id;
            dbClickFlag.value = false;
            dialogVisible.value = true;

            const checkTask = gantt.getTask(id);

            // isRootNode.value = checkTask.parent ;
            console.log(checkTask, checkTask.parent, "checkTask.parent");
            if (String(checkTask.parent) == "0" || !checkTask.parent) {
              isRootNode.value = true;
            } else {
              isRootNode.value = false;
            }
          } else if (e.target.id === "gantt_delete") {
            // gantt.confirm({
            //   title: gantt.locale.labels.confirm_deleting_title,
            //   text: gantt.locale.labels.confirm_deleting,
            //   callback: async res => {
            //     if (res) {
            //       if (route.query.id) {
            //         const params = {
            //           tid: id,
            //           projectProgressId: route.query.id
            //         };
            //         const { code, message } = await postSaveDeletetask(params);
            //         if (code === 200) {
            //           NotifMessage.success("删除成功");
            //           gantt.deleteTask(id);
            //         } else {
            //           NotifMessage.error(message);
            //         }
            //       } else {
            //         gantt.deleteTask(id);
            //       }
            //     }
            //   }
            // });
            ElMessageBox.alert("确定删除该日程？", "删除", {
              showCancelButton: true,
              cancelButtonText: "取消",
              confirmButtonText: "确定",
              type: "warning",
              callback: async action => {
                if (action === "confirm") {
                  if (route.query.id) {
                    const params = {
                      tid: id,
                      projectProgressId: route.query.id
                    };
                    const { code, message } = await postSaveDeletetask(params);
                    if (code === 200) {
                      NotifMessage.success("删除成功");
                      gantt.deleteTask(id);
                    } else {
                      NotifMessage.error(message);
                    }
                  } else {
                    gantt.deleteTask(id);
                  }
                }
              }
            });
          }
          // else if (e.target.id === "gantt_auth_edit") {
          //   if (isFullActive.value) {
          //     handleFull();
          //   }

          //   const checkTask = gantt.getTask(id);
          //   // isEditStatus.value = true;

          //   getGanttCurrentInfo(route.query.id, checkTask.path);
          // }

          // currentGanttId.value = id;

          return true;
        },
        // 给事件命名
        { id: "compare-task-event" }
      );

      // 监听灯箱事件，如果是创建任务灯箱，则隐藏不展示，另作逻辑处理
      // gantt.attachEvent(
      //   "onLightbox",
      //   function () {
      //     console.log(123);
      // gantt.hideLightbox();
      // gantt.attachEvent(
      //   "onTaskCreated",
      //   function () {
      //     gantt.hideLightbox();
      //     return true;
      //   },
      //   null
      // );
      //     return true;
      //   },
      //   null
      // );

      // 甘特图全屏配置，指定dom
      gantt.ext.fullscreen.getFullscreenElement = function () {
        return document.querySelector("#myCover");
      };

      const formatter = gantt.ext.formatters.durationFormatter({
        enter: "day",
        store: "hour",
        format: "day",
        hoursPerDay: 24,
        hoursPerWeek: 40,
        daysPerMonth: 30,
        short: true
      });
      const linksFormatter = gantt.ext.formatters.linkFormatter({
        durationFormatter: formatter
      });

      gantt.templates.rightside_text = function (start, end, task) {
        if (task.type == gantt.config.types.milestone) {
          return task.text;
        }
        return "";
      };

      // gantt.config.layout.init(gantt, formatter, linksFormatter);

      // gantt.config.lightbox.sections = [
      //   {
      //     name: "description",
      //     height: 70,
      //     map_to: "text",
      //     type: "textarea",
      //     focus: true
      //   },
      //   {
      //     name: "progress",
      //     height: 22,
      //     map_to: "progress",
      //     type: "select",
      //     options: [
      //       { key: "0", label: "未开始" },
      //       { key: "0.1", label: "10%" },
      //       { key: "0.2", label: "20%" },
      //       { key: "0.3", label: "30%" },
      //       { key: "0.4", label: "40%" },
      //       { key: "0.5", label: "50%" },
      //       { key: "0.6", label: "60%" },
      //       { key: "0.7", label: "70%" },
      //       { key: "0.8", label: "80%" },
      //       { key: "0.9", label: "90%" },
      //       { key: "1", label: "完成" }
      //     ]
      //   },
      //   { name: "type", type: "typeselect", map_to: "type" },
      //   { name: "time", type: "duration", map_to: "auto" }
      // ];

      // gantt.config.lightbox.milestone_sections = [
      //   {
      //     name: "description",
      //     height: 70,
      //     map_to: "text",
      //     type: "textarea",
      //     focus: true
      //   },
      //   {
      //     name: "type",
      //     type: "typeselect",
      //     map_to: "type"
      //   },
      //   {
      //     name: "time",
      //     type: "duration",
      //     single_date: true,
      //     map_to: "auto",
      //     formatter: formatter
      //   }
      // ];
      // Make resize marker for two columns
      gantt.attachEvent(
        "onColumnResizeStart",
        function (ind, column) {
          if (!column.tree || ind == 0) return;

          setTimeout(function () {
            const marker: any = document.querySelector(
              ".gantt_grid_resize_area"
            );
            if (!marker) return;
            const cols = gantt.getGridColumns();
            const delta = cols[ind - 1].width || 0;
            if (!delta) return;

            marker.style.boxSizing = "content-box";
            marker.style.marginLeft = -delta + "px";
            marker.style.paddingRight = delta + "px";
          }, 1);
        },
        null
      );

      gantt.attachEvent(
        "onCollapse",
        function () {
          const el = document.querySelector(".dhx-navigation");
          if (el) {
            el.removeAttribute("style");
          }

          const chatapp = document.getElementById("chat-application");
          if (chatapp) {
            chatapp.style.visibility = "visible";
          }
        },
        null
      );

      gantt.attachEvent(
        "onExpand",
        function () {
          const el: any = document.querySelector(".dhx-navigation");
          if (el) {
            el.style.position = "static";
          }
          const chatapp = document.getElementById("chat-application");
          if (chatapp) {
            chatapp.style.visibility = "hidden";
          }
        },
        null
      );

      // 添加任务保存事件
      // gantt.attachEvent(
      //   "onLightboxSave",
      //   function () {
      //     let t = gantt.getLightboxValues();
      //     currentGanttId.value = t.id;

      //     console.log(t, "test");

      //     gantt.addTask(t);
      //     gantt.refreshData();
      //     gantt.render();
      //     gantt.hideLightbox();

      //     setTimeout(() => {
      //       emit("emitSaveToGo", currentGanttId.value);
      //     }, 800);

      //     return true;
      //   },
      //   null
      // );

      // 拖拽任务进度事件
      gantt.attachEvent(
        "onAfterTaskDrag",
        async function (id) {
          const taskInfo = gantt.getTask(id);
          if (route.query.id) {
            const params = {
              billId: taskInfo?.billId ?? "",
              billName: taskInfo?.billName ?? "",
              // dprogress: Math.floor(taskInfo.progress * 100) / 100,
              duration: taskInfo.duration,
              editable: taskInfo?.editable ?? "",
              end_date: `${dayjs(taskInfo.end_date).format(
                "YYYY-MM-DD"
              )} 00:00:00`,
              id: taskInfo.id,
              nid: taskInfo?.nid ?? "",
              open: taskInfo?.open ?? "",
              parent: taskInfo?.parent ?? "",
              progress: Math.floor(taskInfo.progress * 100) / 100,
              projectProgressId: route.query.id,
              readonly: taskInfo?.readonly ?? "",
              rollup: taskInfo?.rollup ?? "",
              start_date: `${dayjs(taskInfo.start_date).format(
                "YYYY-MM-DD"
              )} 00:00:00`,
              text: taskInfo?.text ?? "",
              type: taskInfo?.type ?? "",
              wbs: taskInfo?.wbs ?? "",
              privilegeUserId: taskInfo?.privilegeUserId ?? ""
            };
            const { code } = await postSaveUpdatetask(params);
            if (code === 200) {
              NotifMessage.success("进度修改成功");
            }
            // // 取消事件
            // gantt.detachEvent("add-task-progress-event");
          }
          return false;
          // console.log(mode, e, "11");
          // console.log(gantt.getDatastore("task"), "getLineStore");
        },
        { id: "add-task-progress-event" }
      );

      // 新增连线事件
      gantt.attachEvent(
        "onAfterLinkAdd",
        async function (id, item) {
          console.log(id, item);

          if (route.query.id) {
            console.log("edit");
            const params = Object.assign(item, {
              projectProgressId: route.query.id
            });
            const { code, message } = await postSaveAddlink(params);
            if (code === 200) {
              NotifMessage.success("新增连线成功");
            } else {
              NotifMessage.error(message);
            }
            // // 取消事件
            // gantt.detachEvent("add-link-event");
          }
          return false;
        },
        { id: "add-link-event" }
      );

      // 删除连线事件
      gantt.attachEvent(
        "onAfterLinkDelete",
        async function (id) {
          // console.log(id, item);
          if (route.query.id) {
            // console.log("edit");
            const params = {
              tid: id,
              projectProgressId: Number(route.query.id)
            };
            const { code, message } = await postSaveDeletelink(params);
            if (code === 200) {
              NotifMessage.success("删除连线成功");
            } else {
              NotifMessage.error(message);
            }
          }
          return false;
        },
        // null
        // 给事件命名
        { id: "delete-link-event" }
      );

      gantt.attachEvent(
        "onAfterTaskAdd",
        async function (id, item) {
          console.log("enter-add");
          if (route.query.id) {
            const params = {
              billId: item?.billId ?? "",
              billName: item?.billName ?? "",
              // dprogress: Math.floor(item.progress * 100) / 100,
              duration: item.duration,
              editable: item?.editable ?? "",
              end_date: `${dayjs(item.end_date).format("YYYY-MM-DD")} 00:00:00`,
              id: item.id,
              nid: item?.nid ?? "",
              open: item?.open ?? "",
              parent: item?.parent ?? "",
              progress: Math.floor(item.progress * 100) / 100,
              projectProgressId: route.query.id,
              readonly: item?.readonly ?? "",
              rollup: item?.rollup ?? "",
              start_date: `${dayjs(item.start_date).format(
                "YYYY-MM-DD"
              )} 00:00:00`,
              text: item?.text ?? "",
              type: item?.type ?? "",
              wbs: item?.wbs ?? "",
              privilegeUserId: item?.privilegeUserId ?? ""
            };
            const { code } = await postSaveAddtask(params);
            if (code === 200) {
              NotifMessage.success("新建成功");
            } else {
              NotifMessage.error("新建失败");
              gantt.deleteTask(id);
            }
            // // 取消事件
            // gantt.detachEvent("add-task-event");
          }
          // console.log(gantt.getDatastore("task"), "getLineStore");
          console.log("test_btn");
          gantt.open(item.parent);
          return false;
        },
        // 给事件命名
        { id: "add-task-event" }
      );

      gantt.templates.tooltip_text = function (start, end, task) {
        const links = task.$target;
        const labels = [];
        for (let i = 0; i < links.length; i++) {
          const link = gantt.getLink(links[i]);
          labels.push(linksFormatter.format(link));
        }
        const predecessors = labels.join(", ");

        let progressInfo = "";
        if (task.progress <= 1) {
          progressInfo = task.progress
            ? parseInt(Math.round(task.progress * 10000) / 100) + "%"
            : "0%";
        } else {
          progressInfo = parseInt(task.progress) + "%";
        }

        let html =
          "<b>任务:</b> " +
          task.text +
          "<br/><b>开始时间:</b> " +
          gantt.templates.tooltip_date_format(start) +
          // "<br/><b>结束时间:</b> " +
          // gantt.templates.tooltip_date_format(end) +
          "<br><b>工期:</b> " +
          formatter.format(task.duration) +
          "天" +
          "<br><b>进度:</b>" +
          progressInfo;
        if (predecessors) {
          html += "<br><b>继承:</b>" + predecessors;
        }
        // if (task.progress) return html;
        return html;
      };

      // 设置周末颜色
      // @ts-ignore

      // gantt.templates.scale_cell_class = function (date) {
      //   if (!gantt.isWorkTime(date)) {
      //     // return "weekend";
      //   }
      // };
      gantt.templates.timeline_cell_class = function (task, date) {
        const isWeek = gantt.ext.zoom.getCurrentLevel();
        // 判断当前视图为否为周
        if (isWeek === 1) {
          if (!gantt.isWorkTime({ task: task, date: date })) {
            return "weekend";
          }
        }
      };

      gantt.templates.task_text = function (start, end, task) {
        let progressInfo = "";
        if (task.progress <= 1) {
          progressInfo = task.progress
            ? parseInt(Math.round(task.progress * 10000) / 100) + "%"
            : "0%";
        } else {
          progressInfo = parseInt(task.progress) + "%";
        }
        return (
          "<b style='text-align:left;'></b> " +
          task.text +
          "    <span style='text-align:left;'>" +
          "&emsp;" +
          progressInfo +
          "</span>"
        );
      };

      // 配置默认展示树结构
      gantt.config.open_tree_initially = true;

      gantt.config.reorder_grid_columns = true;
      // 禁止用户拖动条形图来改变位置
      gantt.config.drag_move = false;
      // 当task的长度改变时，自动调整图表坐标轴区间用于适配task的长度
      gantt.config.fit_tasks = true;
      // 禁止通过拖拽改变工期
      gantt.config.drag_resize = false;
      //设置按行渲染甘特图提交效率
      gantt.config.show_task_cells = true;
      //设置是否可添加【该配置对源码进行修改后】
      // gantt.config.can_add = true;

      gantt.config.auto_types = false;
      // gantt.config.xml_date = "%Y-%m-%d %H:%i:%s";
      // gantt.config.duration_unit = "hour";

      // gantt.config.row_height = 23;
      // gantt.config.order_branch = "marker";
      // gantt.config.order_branch_free = false;
      gantt.config.grid_resize = true;

      // gantt.config.auto_scheduling_strict = true;
      // ganttModules.zoom.setZoom("months");

      // gantt.config.readonly = true;
      // 禁止单机选中
      gantt.config.select_task = true;
      // 禁止双击弹框
      gantt.config.details_on_dblclick = false;
    }

    function setLocal() {
      // gantt.config.month_date = "%Y年 %M";

      gantt.locale = {
        date: {
          month_full: [
            "一月",
            "二月",
            "三月",
            "四月",
            "五月",
            "六月",
            "七月",
            "八月",
            "九月",
            "十月",
            "十一月",
            "十二月"
          ],
          month_short: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月"
          ],
          day_full: [
            "星期日",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六"
          ],
          day_short: ["日", "一", "二", "三", "四", "五", "六"]
        },
        labels: {
          new_task: "新任务",
          // dhx_cal_today_button: "今天",
          // day_tab: "日",
          // week_tab: "周",
          // month_tab: "月",
          // new_event: "新建日程",
          icon_save: "保存",
          icon_cancel: "关闭",
          icon_details: "详细",
          icon_edit: "编辑",
          icon_delete: "删除",
          confirm_closing: "请确认是否撤销修改!", // Your changes will be lost, are your sure?
          confirm_deleting: "是否删除日程?",
          section_description: "名称",
          section_time: "时间范围",
          section_type: "类型",
          section_progress: "进度",

          /* grid columns */

          column_wbs: "工作分解结构",
          column_text: "任务名",
          column_start_date: "开始时间",
          column_duration: "持续时间",
          column_add: "",

          /* link confirmation */

          link: "关联",
          confirm_link_deleting: "将被删除",
          link_start: " (开始)",
          link_end: " (结束)",

          type_task: "任务",
          type_project: "项目",
          type_milestone: "里程碑",

          minutes: "分钟",
          hours: "小时",
          days: "天",
          weeks: "周",
          months: "月",
          years: "年",

          /* message popup */
          message_ok: "OK",
          message_cancel: "关闭",

          /* constraints */
          section_constraint: "Constraint",
          constraint_type: "Constraint type",
          constraint_date: "Constraint date",
          asap: "As Soon As Possible",
          alap: "As Late As Possible",
          snet: "Start No Earlier Than",
          snlt: "Start No Later Than",
          fnet: "Finish No Earlier Than",
          fnlt: "Finish No Later Than",
          mso: "Must Start On",
          mfo: "Must Finish On",

          /* resource control */
          resources_filter_placeholder: "type to filter",
          resources_filter_label: "hide empty"
        }
      };
    }

    // 导出的方法进行调用
    const exportGanttDatastore = () => {
      const links = Object.values(gantt.getDatastore("link").pull);
      const tasks = Object.values(gantt.getDatastore("task").pull);
      const params = {
        ganttJsonStr: JSON.stringify({ links, tasks }),
        fileName: `${new Date().getTime()}.xml`
      };
      try {
        downloadXml(params);
      } catch (err) {
        console.log(err);
      }
    };

    // 初始化导入的数据
    const initImportData = file => {
      console.log(file, "gantt init");
      gantt.clearAll();
      gantt.config.xml_date = "%Y-%m-%d";
      gantt.init(ganttRef.value);

      gantt.parse(file);
      gantt.render();

      const date_to_str = gantt.date.date_to_str(gantt.config.task_date);
      const today = new Date();
      gantt.addMarker({
        start_date: today,
        css: "today",
        text: "今天",
        title: "今天: " + date_to_str(today)
      });
    };

    const getGantDatastore = () => {
      const links = Object.values(gantt.getDatastore("link").pull);
      const tasks = Object.values(gantt.getDatastore("task").pull);
      emit("getGanttData", { tasks, links });
    };

    const handleChangeType = item => {
      if (item === "project") {
        ruleForm.duration = 1;
        // @ts-ignore
        ruleForm.start_date = new Date();
        ruleForm[`start_date`] = `${dayjs(new Date()).format(
          "YYYY-MM-DD"
        )} 00:00:00`;
      } else if (item === "milestone") {
        ruleForm.duration = 0;
        ruleForm.progress = 0;
      }
    };

    const handleSubmit = async () => {
      // 如果是创建
      const isValid = await new Promise(resolve =>
        ruleFormRef.value.validate(resolve)
      );
      if (!isValid) return;

      if (!dbClickFlag.value) {
        const res = JSON.parse(JSON.stringify(ruleForm));
        console.log(ruleForm, "ruleform");

        res["end_date"] = res[`start_date`] * ruleForm.duration;
        res.progress = res.progress / 100;
        // 新建的数据都可以编辑
        res.canEdit = true;
        if (isRootNode.value) {
          res.canEmpower = isRootNode.value;
        } else {
          res.canEmpower = isRootNode.value;
        }

        if (ruleForm.billName) {
          res.billName = ruleForm.billName.label;
          res.billId = ruleForm.billName.value;
        }

        console.log(currentGanttId.value);

        gantt.addTask(res, currentGanttId.value ? currentGanttId.value : 0);
        gantt.refreshData();
        // gantt.render();

        dialogVisible.value = false;
      } else {
        // 编辑

        const resEdit = JSON.parse(JSON.stringify(ruleForm));

        // if (resEdit?.privilegeUserId) {
        //   userList.value = await searchUserName([resEdit.privilegeUserId]);
        // }

        console.log(currentGanttId.value, "currentGanttId.value", resEdit);
        gantt.getTask(currentGanttId.value).type = resEdit.type;
        gantt.getTask(currentGanttId.value).text = resEdit.text;
        gantt.getTask(currentGanttId.value).progress = resEdit.progress / 100;
        // const newDate =
        //   +dayjs(resEdit.start_date).format("x") + resEdit.duration * 86400000;
        // const endTime = `${dayjs(newDate).format("YYYY-MM-DD")} 00:00:00`;

        const startTime = `${dayjs(resEdit.start_date).format(
          "YYYY-MM-DD"
        )} 00:00:00`;

        // console.log(getWeekday(startTime, endTime), "isWeekDay");
        const end = gantt.calculateEndDate({
          start_date: new Date(startTime),
          duration: resEdit.duration
          // task: resEdit
        });

        const start = gantt.calculateEndDate({
          start_date: new Date(end),
          duration: -resEdit.duration
          // task: resEdit
        });
        console.log(end, "end");

        // gantt.getTask(currentGanttId.value).start_date = new Date(startTime);
        gantt.getTask(currentGanttId.value).start_date = start;
        gantt.getTask(currentGanttId.value).end_date = end;
        gantt.getTask(currentGanttId.value).duration = resEdit.duration;
        gantt.getTask(currentGanttId.value).parent = resEdit.parent;
        gantt.getTask(currentGanttId.value).billName = resEdit.billName;
        gantt.getTask(currentGanttId.value).billId = resEdit.billId;
        // gantt.getTask(currentGanttId.value).users = [
        //   {
        //     resource_id: currentGanttId.value,
        //     duration: resEdit.duration,
        //     mode: "fixedDuration"
        //   }
        // ];
        gantt.getTask(currentGanttId.value).privilegeUserId =
          resEdit.privilegeUserId;

        // @ts-ignore
        gantt.updateTask(currentGanttId.value); //renders the updated task
        // gantt.refreshData();
        // gantt.render();
        dialogVisible.value = false;

        // gantt.render();
        gantt.refreshData();
        if (route.query.id) {
          const params = {
            billId: resEdit?.billId ?? "",
            billName: resEdit?.billName ?? "",
            // dprogress: resEdit.progress / 100,
            duration: resEdit.duration,
            editable: resEdit?.editable ?? "",
            end_date: `${dayjs(end).format("YYYY-MM-DD")} 00:00:00`,
            id: currentGanttId.value,
            nid: resEdit?.nid ?? "",
            open: resEdit?.open ?? "",
            parent: resEdit?.parent ?? "",
            progress: resEdit.progress / 100,
            projectProgressId: route.query.id,
            readonly: resEdit?.readonly ?? "",
            rollup: resEdit?.rollup ?? "",
            start_date: `${dayjs(start).format("YYYY-MM-DD")} 00:00:00`,
            text: resEdit?.text ?? "",
            type: resEdit?.type ?? "",
            wbs: resEdit?.wbs ?? "",
            privilegeUserId: resEdit?.privilegeUserId ?? ""
          };

          const { code } = await postSaveUpdatetask(params);
          if (code === 200) {
            NotifMessage.success("进度修改成功");
          }
        }
      }
    };

    const handleSearch = async query => {
      if (!query) {
        tableData.value = [];
        return;
      }
      const { code, data } = await postBills(
        Object.assign(formSearch, { billName: query })
      );

      if (code === 200) {
        tableData.value = data.list.map(item => {
          return {
            value: item.flowId,
            label: item.billName
          };
        });
      }
    };

    const handleClose = async () => {
      console.log("close");
      dialogVisible.value = false;
      ruleFormRef.value.resetFields();
      ruleForm.type = "";
      ruleForm.text = "";
      ruleForm.progress = 0;
      ruleForm.start_date = "";
      ruleForm.duration = 1;
      ruleForm.parent = 0;
      ruleForm.billId = null;
      ruleForm.billName = null;
      ruleForm.privilegeUserId = "";
      formSearch.billType = "";
      tableData.value = [];
      currentGanttId.value = 0;
      dbClickFlag.value = false;
      isCanEmpower.value = false;
      isRootNode.value = false;
    };

    const handleFull = () => {
      pureSetting.isHiddenSidebarSetting(false);
      isFullActive.value = !isFullActive.value;
      gantt.ext.fullscreen.toggle();
    };

    const handleYear = () => {
      gantt.ext.zoom.setLevel("year");
    };
    const handleMonth = () => {
      gantt.ext.zoom.setLevel("month");
    };
    const handleWeek = () => {
      gantt.ext.zoom.setLevel("week");
    };
    const handleDay = () => {
      gantt.ext.zoom.setLevel("day");
    };

    const handleExpend = () => {
      gantt.config.show_grid = !gantt.config.show_grid;
      gantt.render();
      isGridView.value = !isGridView.value;
    };

    // 导入数据
    const handleFileChange = files => {
      if (files) {
        console.log(123123, "导入");
        initImportData(files);
      }
    };
    // 导出数据
    const exportGanttData = () => {
      exportGanttDatastore();
    };

    onBeforeMount(() => {
      useEventListener("resize", function () {
        if (document.body.scrollHeight - window.screen.height !== 0) {
          pureSetting.isHiddenSidebarSetting(true);
          isFullActive.value = true;
          // isEditStatus.value = props.projectLeader;
          console.log("缩小视图");
          getDataDetialInfo();
        }
      });
    });

    setting();
    setLocal();
    onMounted(() => {
      nextTick(() => {
        // gantt.config.readonly = false;
        gantt.clearAll();
        gantt.config.xml_date = "%Y-%m-%d";
        gantt.init(ganttRef.value);
        console.log(props.tasks, "props.tasks");
        gantt.parse(props.tasks);
        // gantt.parse(test);
        gantt.render();

        console.log(props.projectLeader, "props.projectLeader");
        // if (!props.projectLeader) {
        //   gantt.config.readonly = true;
        // }

        const date_to_str = gantt.date.date_to_str(gantt.config.task_date);
        const today = new Date();
        gantt.addMarker({
          start_date: today,
          css: "today",
          text: "今天",
          title: "今天: " + date_to_str(today)
        });
        // const start = new Date(2019, 8, 22);
        // gantt.addMarker({
        //   start_date: start,
        //   css: "status_line",
        //   text: "开始实施",
        //   title: "开始实施: " + date_to_str(start)
        // });
      });
    });

    onUnmounted(() => {
      // @ts-ignore
      // var myGantt = gantt.getGanttInstance();
      // gantt.destructor();
      // gantt.eventRemove;
    });
    const onParseint = () => {
      ruleForm.progress = parseInt(ruleForm.progress);
    };

    async function getTableData(query = "") {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return {
              value: item.id,
              label: `${item.name}(${item.userName})`
            };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    getTableData();

    // async function getGanttCurrentInfo(id, path) {
    //   try {
    //     const params = {
    //       id,
    //       path
    //     };
    //     const { code, data } = await postGetGanttCurrentInfo(params);
    //     if (code === 200) {
    //       const tasks = {
    //         data: JSON.parse(data).tasks,
    //         links: JSON.parse(data).links
    //       };
    //       console.log(tasks, "data");
    //       // nextTick(() => {
    //       gantt.clearAll();
    //       gantt.config.xml_date = "%Y-%m-%d";
    //       gantt.init(ganttRef.value);
    //       gantt.parse(tasks);
    //       gantt.render();

    //       const date_to_str = gantt.date.date_to_str(gantt.config.task_date);
    //       const today = new Date();
    //       gantt.addMarker({
    //         start_date: today,
    //         css: "today",
    //         text: "今天",
    //         title: "今天: " + date_to_str(today)
    //       });
    //       // const start = new Date(2019, 8, 22);
    //       // gantt.addMarker({
    //       //   start_date: start,
    //       //   css: "status_line",
    //       //   text: "开始实施",
    //       //   title: "开始实施: " + date_to_str(start)
    //       // });
    //       // });
    //     }
    //   } catch (err) {
    //     console.log(err);
    //   }
    // }

    // 获取详情
    const getDataDetialInfo = async () => {
      try {
        const { query } = unref(route);
        if (!query?.id) return;
        const params = {
          id: query?.id
        };
        const { code, data } = await postProgressInfo(params);
        if (code === 200) {
          const tasks = {
            data: JSON.parse(data.progressGanttChart).tasks,
            links: JSON.parse(data.progressGanttChart).links
          };
          gantt.clearAll();
          gantt.config.xml_date = "%Y-%m-%d";
          gantt.init(ganttRef.value);
          gantt.parse(tasks);
          gantt.render();

          const date_to_str = gantt.date.date_to_str(gantt.config.task_date);
          const today = new Date();
          gantt.addMarker({
            start_date: today,
            css: "today",
            text: "今天",
            title: "今天: " + date_to_str(today)
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 根据id 查询用户名
    const searchUserName = async userList => {
      if (!userList.length) return;
      let promises = userList.map(user => {
        return postUserInfo({ id: user });
      });
      let results = await Promise.all(promises);
      // console.log(results, "results");
      const users = results.map(item => {
        return {
          value: (item as any)?.data.id,
          label: `${(item as any)?.data.name}(${(item as any)?.data.userName})`
        };
      });

      return users;
    };

    return {
      ruleFormRef,
      ganttRef,
      typeList,
      ruleForm,
      rulesRules,
      dialogVisible,
      headerTitle,
      currentGanttId,
      formSearch,
      dbClickFlag,
      tableData,
      isFullActive,
      isGridView,
      isCanEmpower,
      isRootNode,
      userList,
      isEditStatus,
      onParseint,
      handleExpend,
      handleFull,
      handleYear,
      handleMonth,
      handleWeek,
      handleDay,
      handleSearch,
      handleClose,
      handleChangeType,
      handleFileChange,
      exportGanttData,
      getGantDatastore,
      exportGanttDatastore,
      handleSubmit,
      initImportData,
      getTableData
    };
  }
});
</script>

<style lang="scss" scoped>
// .deadline {
//   position: absolute;
//   border-radius: 12px;
//   border: 2px solid #585858;
//   -moz-box-sizing: border-box;
//   box-sizing: border-box;
//   width: 14px;
//   height: 14px;
//   margin-left: -7px;
//   margin-top: 6px;
//   z-index: 1;
//   background: red;
// }

#myCover {
  width: 100%;
  height: 550px;
  // position: static;
  .gantt__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 40px;
    padding: 0 10px;
    background: #fff;
    &--left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .upload-btn {
        margin-right: 5px;
      }
    }
  }
  .gantt__wrap {
    width: 100%;
    height: calc(100% - 40px);
  }
}

.dialog-wrap {
  padding: 0 20px;
}
:deep .el-select {
  width: 100%;
}
:deep .el-date-editor {
  width: 100%;
}
</style>
<style lang="scss">
.setZindex {
  z-index: 1002 !important;
}

.hideElement {
  display: none;
}

.fa {
  cursor: pointer;
  font-size: 14px;
  text-align: center;
  opacity: 0.5;
  padding: 5px;
}

.fa:hover {
  opacity: 1;
}

.fa-pencil {
  color: #ffa011;
}

.fa-plus {
  color: #328ea0;
}

.fa-times {
  color: red;
}
// 截断超长文本
.gantt_tree_content {
  overflow: hidden;
  text-overflow: ellipsis;
}
.gantt_btn_set.gantt_delete_btn_set {
  float: right;
}
.gantt_btn_set {
  float: right;
}

.gantt-fullscreen {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 30px;
  height: 30px;
  padding: 2px;
  font-size: 32px;
  background: transparent;
  cursor: pointer;
  opacity: 0.5;
  text-align: center;
  -webkit-transition: background-color 0.5s, opacity 0.5s;
  transition: background-color 0.5s, opacity 0.5s;
}

.gantt-fullscreen:hover {
  background: rgba(150, 150, 150, 0.5);
  opacity: 1;
}

.weekend {
  background: #e6e7e6;
}

// .gantt_selected .weekend {
//   background: #f7eb91;
// }

// --------------------------------------

// .left-container {
//   height: 800px;
// }
// /* 左侧菜单字 */
// .gantt_grid_head_cell {
//   font-size: 14px;
//   font-weight: bold;
// }
// .gantt_grid_scale .gantt_grid_head_cell {
//   color: rgb(28, 160, 127);
// }
/* 右侧条 */
.gantt_task_line {
  border-radius: 55px;
}
.gantt_task_line {
  background-color: #448aff;
  border: 1px solid #448aff;
}
.gantt_task_progress {
  /* background-color:rgb(243, 224, 78); */
  background-color: #246cd9;
  /* background-color:#42b983 */
}

.gantt_task_line.gantt_project {
  background-color: #1de9b6;
  border: 1px solid #1de9b6;
}

// /* 选中 */
.gantt_task_row.gantt_selected {
  // background: #f8ec3c31;
  background: rgba(0, 199, 181, 0.2);
}
.gantt_grid_data .gantt_row.gantt_selected {
  // background: #f8ec3c31;
  background: rgba(0, 199, 181, 0.2);
}

.gantt_grid_data .gantt_row.odd:hover,
.gantt_grid_data .gantt_row:hover,
.gantt_grid_data .gantt_row.gantt_selected,
.gantt_grid_data .gantt_row.odd.gantt_selected,
.gantt_task_row.gantt_selected {
  // background-color: cyan;
  background: rgba(0, 199, 181, 0.2);
}
.gantt_grid_data .gantt_row.odd.gantt_selected {
  background: rgba(0, 199, 181, 0.2);
  // background: #f8ec3c31;
}
// /* 表格线 */
// .gantt_task_cell {
//   border-right: 0;
// }
// /* 左侧图标 打开 */
// /* 主干 */
// .gantt_tree_icon.gantt_folder_open {
//   background-image: url("https://i.52112.com/icon/jpg/256/20200821/88749/3687127.jpg");
//   width: 12px;
//   height: 100%;
//   background-size: contain;
//   background-position: 50%;
//   margin-right: 0.3rem;
// }
// /* 分支 */
// .gantt_tree_icon.gantt_file {
//   background-image: url("https://i.52112.com/icon/jpg/256/20200729/85619/3735480.jpg");
//   width: 12px;
//   height: 100%;
//   background-size: contain;
//   background-position: 50%;
//   margin-right: 0.3rem;
// }
// /* 加号 */
// .gantt_tree_icon.gantt_open {
//   background-image: url("https://i.52112.com/icon/jpg/256/20161117/3733/197524.jpg");
//   width: 12px;
//   height: 100%;
//   background-size: contain;
//   background-position: 50%;
//   margin-right: 0.3rem;
// }
// /* 左侧图标 关闭 */
// /* 主干 */
// .gantt_tree_icon.gantt_folder_closed {
//   background-image: url("https://i.52112.com/icon/jpg/256/20200821/88749/3687127.jpg");
//   width: 12px;
//   height: 100%;
//   background-size: contain;
//   background-position: 50%;
//   margin-right: 0.3rem;
// }
// /* 减号 */
// .gantt_tree_icon.gantt_close {
//   background-image: url("https://i.52112.com/icon/jpg/256/20190807/52484/2373424.jpg");
//   width: 12px;
//   height: 100%;
//   background-size: contain;
//   background-position: 50%;
//   margin-right: 0.3rem;
// }
// /* 左侧背景 */
// .gantt_grid_scale {
//   background-color: #11a98318;
// }
// .gantt_grid_data {
//   /* background-color:#11a98318 */
//   background-color: #11a98318;
// }
// /* 右侧横条弹框 */
// .gantt_btn_set.gantt_save_btn_set {
//   background-color: #1890ff;
// }
// .gantt_btn_set.gantt_delete_btn_set {
//   background-color: rgb(224, 21, 21);
// }
// .gantt_btn_set.gantt_cancel_btn_set {
//   background-color: rgba(150, 153, 156, 0.27);
// }
// // 导入数据框大小
// .gantt_modal_box {
//   width: 600px;
// }

// .gantt_popup_text table {
//   margin: auto;
// }
</style>
